<template>
  <div id="p-homePage">
    <van-nav-bar class="header" fixed :border="false">
      <div class="title" slot="title">图小助</div>
      <div class="right" slot="right">
        <img src="@/assets/img/public/service.png" @click="goToService()" width="100%" alt />
      </div>
    </van-nav-bar>

    <div class="main" :style="{'height':curHeight}">
      <div class="swipercon">
        <div class="swpierbg"></div>
        <div class="swiper">
          <!-- banner -->
          <van-swipe :autoplay="3000">
            <van-swipe-item v-for="(image, index) in images" :key="index">
              <!-- <van-image lazy-load :src="image" width="100%" height="100%"></van-image> -->
              <img :src="image" width="100%" height="100%" alt />
            </van-swipe-item>
          </van-swipe>
        </div>
      </div>
      <!-- 公告栏 -->
      <div class="noticeBar">
        <van-notice-bar
          :text="noticeText"
          background="#F9F9F9"
          color="#282828"
          left-icon="volume-o"
        />
      </div>
      <!-- iconGrouop -->
      <div class="btngroup flex flex-space-a">
        <div
          class="btnlist flex flex-center-y flex-col"
          v-for="(item,index) in iconList"
          @click="gorouter(item.link)"
          :key="index"
        >
          <div class="btnimg">
            <img :src="item.img" width="100%" alt />
          </div>
          <div>{{item.text}}</div>
        </div>
      </div>
      <div ref="btngroupGap"></div>
      <!-- 下拉刷新部分 -->
      <van-pull-refresh
        v-model="isLoading"
        @refresh="onRefresh"
        class="vanRefresh"
        v-show="order!='0'"
        :style="{
           height: `calc(100vh - ${pullOverflowHeight}px)`
        }"
      >
        <div class="noNetWord" v-if="order==3">
          <div>
            <img src="../../../assets/img/public/nophone.png" alt />
            <p>暂无网络</p>
          </div>
        </div>
        <order-card
          @open_popup="() => 0"
          @updateOrder="updateOrder"
          @successPay="() => 0"
          @changePay="() => 0"
          :form="form"
          :type="role"
          :groupUids="groupUids"
          v-show="order=='1'"
          v-if="form"
        />

        <!-- TODO 缺少status role -->
      </van-pull-refresh>
      <div class="noOrder" v-show="order=='0'">
        <div class="orderimg">
          <img src="@/assets/img/performance/homePage/noorder.png" width="100%" alt />
        </div>
        <div class="fz4 wordsGray notitle">暂无订单</div>
      </div>
    </div>
    <main-nav></main-nav>
    <van-dialog
      v-model="isNew"
      confirm-button-text="确认"
      confirm-button-color="#5E8EFE"
      cancel-button-text="退出"
      cancel-button-color="#000000"
      show-cancel-button
      show-confirm-button
      @confirm="confirmMoney"
      @cancel="cancelMoney"
    >
      <div class="dialog-case">
        <div class="header-case">前往缴纳服务保证金</div>
        <div class="content-words">平台规定表现师需缴纳一定的服务保证金才能在平台进行接单赚钱，后期根据您的信用有所奖励及扣除。</div>
      </div>
    </van-dialog>
  </div>
</template>
<script>
import Vue from "vue";
import { Dialog } from "vant";
Vue.use(Dialog);
import { mapMutations } from "vuex";
import mainNav from "@/components/performance/mainNav";
//import itemCard from "@/components/performance/homePage/itemCard";
// import itemCard from "@/components/designer/orderCenter/orderCard";
import orderCard from "@/components/designer/orderCenter/orderCard.vue";
import {
  getuserUid,
  setVersionNo,
  getPassword,
  removeRole,
  removeToken,
  removeuserUid,
  getUserLogin,
  setUserInfo,
  getRole
} from "@/utils/auth.js";
import { getRemind } from "@/utils/chat.js";
export default {
  components: {
    mainNav,
    orderCard
  },
  data() {
    return {
      groupUids: getRemind(),
      order: "1",
      images: [require("@/assets/img/performance/homePage/swiper.png")],
      btnList: [
        {
          img: require("@/assets/img/performance/homePage/worksCenter.png"),
          text: "作品中心",
          link: "/performance/worksCenter"
        },
        {
          img: require("@/assets/img/performance/homePage/timeManage.png"),
          text: "时间管理",
          link: "/performance/timeManage"
        },
        {
          img: require("@/assets/img/performance/homePage/serviceRange.png"),
          text: "服务范围",
          link: "/service_scope"
        },
        {
          img: require("@/assets/img/performance/homePage/regular.png"),
          text: "平台规则",
          link: "/performance/platFormRules"
        }
      ],
      iconList: [],
      itemForm: {
        name: "万科云城项目组",
        worksNum: "3张",
        firstTime: "09/19 07:00",
        date: "09月19、21、22",
        address: "深圳南山区科慧路一号沛鸿大厦二楼216室可飞猪科技"
      },
      fixedHeight: "50",
      isNew: false, // 变量 表现师判断是不是初次进去
      noticeText: "",
      //控制下拉刷新
      isLoading: false,
      form: false,
      newVersionNo: "", // 新版本号
      downUrl: "", // 旧版本返回更新版本地址
      // 循环监听订单
      isLoopOrder: false,
      role: "",
      roleType: "",
      pullOverflowHeight: '0px'
    };
  },
  created() {
    this.getVersion();
    this.setTabIndexP(0);
    // this.getInfo(); //获取首页信息
    let loop = () => {
      if (this.isLoopOrder) {
        this.getInfo();
        setTimeout(loop, 5e3);
      }
    };
    this.isLoopOrder = true;
    loop();
  },
  watch: {
    iconList(val) {}
  },
  mounted() {
    //连接环信
    this.$imoption.user = getuserUid(); //环信账号
    this.$imoption.pwd = getPassword(); //环信密码
    this.$imconn.open(this.$imoption); //建立连接
    //this.$imconn.setPresence(); //登录环信
    this.getUserInfo();
    setTimeout(() => {
      this.getMenu();
    }, 500);

    let btngroupGap = this.$refs.btngroupGap
    this.pullOverflowHeight = btngroupGap.getBoundingClientRect().top + (+this.fixedHeight)
  },
  methods: {
    getMenu() {
      this.iconList = this.btnList;
      if (this.roleType === 3) {
        this.btnList.splice(2, 1);
        this.iconList = this.btnList;
      } else {
        this.iconList = this.btnList;
      }
    },
    updateOrder() {
      this.getInfo();
    },
    gorouter(link) {
      this.$router.push(link);
    },
    getUserInfo() {
      HTTP("userCenter", {
        userUid: getuserUid()
      }).then(res => {
        if (res.code == 200) {
          setUserInfo(res.data);
        }
      });
    },
    // 初次进来 确认  保证金 跳转保证金
    confirmMoney() {
      this.$router.push("/performance/forDeposit");
    },
    // 初次进来 退出 保证金 清楚缓存（未） + 跳出 登录
    cancelMoney() {
      removeToken();
      removeuserUid();
      removeRole();
      setTimeout(this.$router.push({ name: "login" }), 2000);
      this.$router.push("/login");
    },
    goToService() {
      this.$router.push("/advisory");
    },
    //获取首页信息
    async getInfo() {
      try {
        const e = await HTTP("getIndexList", {
          userUid: getuserUid()
        });
        if (e.code === 200) {
          this.roleType = e.data.role;
          this.role = e.data.role === 2 ? "2" : e.data.role === 3 ? "3" : "-1";
          if (
            e.data.sysAnnouncement == null ||
            e.data.sysAnnouncement == "" ||
            e.data.sysAnnouncement.content == null ||
            e.data.sysAnnouncement.content == ""
          ) {
            this.noticeText = "暂无公告";
          } else {
            this.noticeText = e.data.sysAnnouncement.content;
          }
          if (e.data.orderInfo == null || e.data.orderInfo.length == 0) {
            this.order = "0";
          } else {
            this.form = e.data.orderInfo;
          }
          //banner图片
          let arr = e.data.sysBanners;
          this.images = [];
          arr.forEach(item => {
            this.images.push(item.imageUrl);
          });
          console.log("order", this.order);
        } else {
          this.$toast(e.msg);
        }
      } catch (error) {
        this.order = "3";
        console.log("performance", error);
      }
    },
    onRefresh() {
      this.form = null;
      setTimeout(() => {
        this.$nextTick(() => {
          this.getInfo();
        });
        this.$toast("刷新成功");
        this.isLoading = false;
      }, 100);
    },
    // 检查是否需要缴纳押金
    async selectUserIsPay() {
      const SPC = await HTTP("selectUserIsPay", {
        userUid: getuserUid()
      });
      if (SPC.code == 200) {
        this.isNew = SPC.data.isPay;
        this.setPayCashMoney(SPC.data.payCashMoney);
      } else {
        this.$toast(SPC.msg || "服务器异常");
      }
    },
    // 版本检测
    async getVersion() {
      const SPC = await HTTP("getVersion", {
        version: this.$v
      });
      if (SPC.code == 200) {
        if (SPC.data.version) {
          setVersionNo(SPC.data.version)
        } else {
          setVersionNo('1.0')
        }
        this.downUrl = SPC.data.downUrl;
        if (this.downUrl) {
          // 弹框立即下载
          Dialog.alert({
            title: "有新版本啦！",
            message: "更新更全功能，给您更好的使用体验",
            confirmButtonText: "立即升级"
          }).then(() => {
            this.jumpToAppMarket();
          });
        } else if (!this.downUrl) {
          // 先判断是不是是最新版本 不是（downUrl空是，直接执行判断isPay是够为true，true需要交保证金）
          this.selectUserIsPay();
        }
      } else {
        this.$toast(SPC.msg || "服务器异常");
      }
    },
    //跳转第三方应用平台
    jumpToAppMarket() {
      let _this = this;
      if (window.plus.os.name == "iOS") {
        location.href = 'https://apps.apple.com/cn/app/%E5%9B%BE%E5%B0%8F%E5%8A%A9-%E5%AE%A4%E5%86%85%E6%95%88%E6%9E%9C%E5%9B%BE%E4%B8%8A%E9%97%A8%E6%9C%8D%E5%8A%A1/id1471613155?from=singlemessage&isappinstalled=0';
        const toastI = _this.$toast.loading({
          duration: 3000, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          message: "上APP Store, 有最新版本哦~"
        });
        let secondI = 3;
        const timerI = setInterval(() => {
          secondI--;
          if (!secondI) {
            clearInterval(timerI);
            // _this.$toast.clear();
          }
        }, 3000);
      } else if (window.plus.os.name == "Android") {
		  location.href =  'https://a.app.qq.com/o/simple.jsp?pkgname=io.dcloud.H59C01B9C&from=singlemessage&isappinstalled=0'
      }
    },
    ...mapMutations(["setPayCashMoney", "setTabIndexP"])
  },
  beforeMount() {
    var h = document.documentElement.clientHeight || document.body.clientHeight;
    this.curHeight = h - this.fixedHeight + "px"; //减去页面上固定高度height
  },
  destroyed() {
    this.isLoopOrder = false;
  }
};
</script>
<style lang="scss" scoped>
#p-homePage {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .header {
    background: $color-primary;

    .title {
      color: #ffffff;
    }
    .right {
      width: 0.38rem;
      img {
        position: relative;
        top: 0.13rem;
      }
    }
  }
  .main {
    overflow: hidden;
    .swipercon {
      margin-top: 46px;
      position: relative;
      height: 2.56rem;
      .swpierbg {
        position: absolute;
        width: 100%;
        background-color: $color-primary;
        height: 2.26rem;
      }
      .swiper {
        position: absolute;
        width: 94%;
        left: 3%;
        top: 0.3rem;
        border-radius: 0.1rem;
        overflow: hidden;
      }
    }
    .noticeBar {
      border-bottom: #e5e5e5 1px solid;
      width: 94%;
      margin: auto;
    }
    .btngroup {
      margin: 0.4rem 0;
      height: 1.2rem;
      width: 100%;
      .btnlist {
        text-align: center;
        height: 1.2rem;
        width: 100%;

        .btnimg {
          width: 1rem;
          height: 1.1rem;
        }
      }
    }
    .vanRefresh {
      overflow: auto;
      position: relative;
    }
    .noOrder {
      margin-top: 1rem;
      .orderimg {
        width: 3.74rem;
        margin: auto;
      }
      .notitle {
        text-align: center;
      }
    }
  }
  .dialog-case {
    box-sizing: border-box;
    padding: 0.4rem;
    .header-case {
      width: 100%;
      color: #080808;
      line-height: 0.5rem;
      font-family: PingFangSC-Regular;
      font-size: 0.36rem;
      text-align: center;
    }
    .content-words {
      margin-top: 0.2rem;
      color: #9b9b9b;
      font-size: 0.3rem;
      font-family: PingFangSC-Regular;
      line-height: 0.42rem;
      text-align: center;
      text-indent: 0.2rem;
    }
  }
  .noNetWord {
    display: flex;
    justify-content: center;
    > div:nth-child(1) {
      display: flex;
      flex-direction: column;
      align-items: center;
      img {
        width: 3.8rem;
        height: 3rem;
      }
      p {
        font-size: 0.32rem;
        color: #959595;
      }
    }
  }
}
</style>

<style lang="scss">
#p-homePage {
  .van-swipe-item {
    height: 2.26rem !important;
    border-radius: 0.2rem !important;
    img {
      object-fit: cover;
    }
  }
}
</style>
